package com.mark.search.config;


import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.elasticsearch.client.NodeSelector;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;

/**
 * @author : mark
 * @desc : es配置
 * @since : 2022/7/08 16:36
 */
@Import(EsConfig.class)
public class RestHighLevelClientConfig {

    @Bean
    public RestHighLevelClient restHighLevelClient(EsConfig esConfig) {
        HttpHost[] httpHostArray = new HttpHost[1];
        httpHostArray[0] = new HttpHost(esConfig.getHost(), Integer.valueOf(esConfig.getPort()));
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(esConfig.getUserName(), esConfig.getPassword()));

        final RestClientBuilder restClientBuilder = RestClient.builder(httpHostArray)
                .setRequestConfigCallback(requestConfigBuilder ->
                        requestConfigBuilder.setConnectTimeout(esConfig.getConnectTimeOut())
                                .setSocketTimeout(esConfig.getSocketTimeOut())
                                .setConnectionRequestTimeout(esConfig.getConnectionRequestTimeOut())
                ).setHttpClientConfigCallback(httpClientBuilder ->
                        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
                                .setMaxConnTotal(esConfig.getMaxConnectNum())
                                .setMaxConnPerRoute(esConfig.getMaxConnectPerRoute())
                                .setDefaultIOReactorConfig(IOReactorConfig.custom()
                                        .setSoKeepAlive(true)
                                        .build()))
                .setNodeSelector(NodeSelector.SKIP_DEDICATED_MASTERS);

        RestHighLevelClient restHighLevelClient = new RestHighLevelClient(restClientBuilder);
        return restHighLevelClient;

    }
}
